<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import EnvCards from './components/EnvCards.vue'
import MessagePanel from './components/MessagePanel.vue'
import CampusMap from './components/CampusMap.vue'
import ChartContainer from './components/ChartContainer.vue'
import ParticleBackground from './components/ParticleBackground.vue'
import MainTitle from './components/MainTitle.vue'
import TechScanEffect from './components/TechScanEffect.vue'
import HumidityTrend from './components/HumidityTrend.vue'
import { MessageGenerator, BuildingGenerator, EnergyDataGenerator } from './utils/dataGenerator'
import { TemperatureChartConfig, HumidityGaugeConfig, EnvironmentRadarConfig, EnergyBarConfig } from './utils/chartConfig'
import { NewWeatherService } from './services/newWeatherService'
import { HuaweiCloudIoTService } from './services/huaweiCloudIoTService'
import { MockDataService } from './services/mockDataService'
import type { EnvData, MessageItem, BuildingStatus } from './types'

// 响应式数据
const envData = ref<EnvData>({
  temperature: 25,
  humidity: 65,
  pressure: 1013,
  airQuality: 85,
  uvIndex: 6,
  lightIntensity: 800,
  windSpeed: 3.5,
  pm25: 25
})
const messageList = ref<MessageItem[]>(MessageGenerator.generateMessageList())
const buildingList = ref<BuildingStatus[]>(BuildingGenerator.generateBuildingStatus())

// 图表配置
const temperatureChartOptions = ref<any>(null)
const humidityGaugeOptions = ref<any>(null)
const environmentRadarOptions = ref<any>(null)
const energyBarOptions = ref<any>(null)

let updateTimer: number | null = null

// 初始化图表
const initCharts = async () => {
  try {
    // 尝试获取真实天气数据生成24小时温度趋势
    const weatherData = await NewWeatherService.getWeatherData();
    let tempData;
    
    if (weatherData) {
      tempData = NewWeatherService.generate24HourTemperatureTrend(weatherData);
      console.log('✅ 使用真实天气数据生成24小时温度趋势');
    } else {
      // 备用方案：使用模拟数据生成从当前时间开始的24小时趋势
      const currentHour = new Date().getHours();
      tempData = Array.from({ length: 24 }, (_, i) => {
        const actualHour = (currentHour + i) % 24;
        let baseTemp: number;
        
        if (actualHour >= 0 && actualHour < 6) {
          baseTemp = 27 + Math.sin((actualHour + 18) / 24 * Math.PI * 2) * 1;
        } else if (actualHour >= 6 && actualHour < 12) {
          baseTemp = 27 + (actualHour - 6) / 6 * 5;
        } else if (actualHour >= 12 && actualHour < 18) {
          baseTemp = 32 + Math.sin((actualHour - 12) / 6 * Math.PI) * 1;
        } else {
          baseTemp = 33 - (actualHour - 18) / 6 * 4;
        }
        
        return {
          name: '温度',
          value: Math.round((baseTemp + (Math.random() - 0.5) * 0.5) * 10) / 10,
          time: `${(currentHour + i) % 24}:00`
        };
      });
      console.log('⚠️ 使用模拟数据生成24小时温度趋势');
    }
    
    temperatureChartOptions.value = TemperatureChartConfig.create(tempData);
  } catch (error) {
    console.error('❌ 初始化图表失败:', error);
    
    // 最终备用方案
    const currentHour = new Date().getHours();
    const tempData = Array.from({ length: 24 }, (_, i) => {
      const actualHour = (currentHour + i) % 24;
      let baseTemp = 28 + Math.sin((actualHour - 12) / 24 * Math.PI * 2) * 5;
      
      return {
        name: '温度',
        value: Math.round((baseTemp + (Math.random() - 0.5) * 0.5) * 10) / 10,
        time: `${(currentHour + i) % 24}:00`
      };
    });
    
    temperatureChartOptions.value = TemperatureChartConfig.create(tempData);
  }
  
  humidityGaugeOptions.value = HumidityGaugeConfig.create(envData.value.humidity || 79);
  
  const radarData = [
    envData.value.airQuality || 85,
    envData.value.temperature ? envData.value.temperature * 4 : 120,
    envData.value.humidity || 79,
    (envData.value.lightIntensity || 1000) / 20,
    (envData.value.uvIndex || 5) * 10,
    (envData.value.pressure || 1000) - 950
  ];
  environmentRadarOptions.value = EnvironmentRadarConfig.create(radarData);
  
  const energyData = EnergyDataGenerator.generateEnergyData();
  energyBarOptions.value = EnergyBarConfig.create(energyData.categories, energyData.buildings, energyData.data);
};

// 更新数据
const updateData = async () => {
  const hour = new Date().getHours();
  
  try {
    // 尝试获取新的天气API数据
    const weatherData = await NewWeatherService.getWeatherData();
    
    if (weatherData) {
      // 计算当前温度和湿度
      const currentTemp = NewWeatherService.calculateCurrentTemperature(weatherData);
      const currentHumidity = NewWeatherService.calculateCurrentHumidity(weatherData, currentTemp);
      const uvIndex = NewWeatherService.calculateUVIndex(weatherData);
      const airQualityIndex = NewWeatherService.getAirQualityIndex(weatherData);
      
      envData.value = {
        temperature: currentTemp,
        humidity: currentHumidity,
        pressure: Math.round(1013 + (Math.random() - 0.5) * 3), // 气压变化较小
        airQuality: airQualityIndex,
        uvIndex: uvIndex,
        lightIntensity: hour >= 6 && hour <= 18 ? Math.round(400 + Math.sin((hour - 12) / 6 * Math.PI) * 600) : Math.round(Math.random() * 50),
        windSpeed: Math.round((2 + Math.random() * 3) * 10) / 10,
        pm25: Math.round(weatherData.data.pm25)
      };
      
      console.log('✅ 已更新真实天气数据:', {
        城市: weatherData.cityInfo.city,
        当前天气: weatherData.data.forecast[0].type,
        当前温度: `${envData.value.temperature}°C`,
        当前湿度: `${envData.value.humidity}%`,
        空气质量: weatherData.data.quality,
        'PM2.5': weatherData.data.pm25,
        UV指数: uvIndex
      });
    } else {
      throw new Error('获取天气数据失败');
    }
  } catch (error) {
    console.warn('⚠️ 获取天气数据失败，使用模拟数据:', error);
    
    // 备用方案：使用更真实的模拟数据
    let baseTemp: number;
    if (hour >= 0 && hour < 6) {
      baseTemp = 27 + Math.sin((hour + 18) / 24 * Math.PI * 2) * 1;
    } else if (hour >= 6 && hour < 12) {
      baseTemp = 27 + (hour - 6) / 6 * 5;
    } else if (hour >= 12 && hour < 18) {
      baseTemp = 32 + Math.sin((hour - 12) / 6 * Math.PI) * 1;
    } else {
      baseTemp = 33 - (hour - 18) / 6 * 4;
    }
    
    const currentTemp = Math.round((baseTemp + (Math.random() - 0.5) * 0.5) * 10) / 10;
    
    // 修正湿度计算 - 确保在合理范围内(71-92%)
    const baseHumidity = 79; // 平均湿度79.48%
    const tempHumidityFactor = Math.max(0.85, Math.min(1.15, (35 - currentTemp) / 10)); // 温度对湿度的影响
    const timeHumidityFactor = hour >= 12 && hour <= 16 ? 0.92 : 1.08; // 时间对湿度的影响
    const randomFactor = 0.95 + Math.random() * 0.1; // 小范围随机波动
    
    let calculatedHumidity = baseHumidity * tempHumidityFactor * timeHumidityFactor * randomFactor;
    calculatedHumidity = Math.max(71, Math.min(92, Math.round(calculatedHumidity))); // 确保在71-92%范围内
    
    envData.value = {
      temperature: currentTemp,
      humidity: calculatedHumidity, // 使用修正后的湿度值
      pressure: Math.round(1013 + Math.sin(hour / 24 * Math.PI * 2) * 3),
      airQuality: Math.round(80 + Math.random() * 10),
      uvIndex: hour >= 7 && hour <= 17 ? Math.round((6 + Math.sin((hour - 12) / 5 * Math.PI) * 3) * 10) / 10 : 0,
      lightIntensity: hour >= 6 && hour <= 18 ? Math.round(400 + Math.sin((hour - 12) / 6 * Math.PI) * 600) : Math.round(Math.random() * 50),
      windSpeed: Math.round((2 + Math.random() * 3) * 10) / 10,
      pm25: Math.round(25 + Math.random() * 15)
    };
  }
  
  // 获取华为云IoT设备消息
  try {
    console.log('🌐 正在获取华为云IoT设备消息...');
    console.log('🕐 当前时间:', new Date().toISOString());
    
    // 由于1秒更新一次，减少缓存清理频率，只在必要时清理
    const shouldClearCache = Math.random() < 0.02; // 降低到2% 概率清空缓存
    if (shouldClearCache) {
      console.log('🗑️ 定期清空设备缓存以确保状态变化检测');
      HuaweiCloudIoTService.clearDeviceCache();
    }
    
    // 显示当前缓存状态
    const cacheStatus = HuaweiCloudIoTService.getDeviceCacheStatus();
    console.log('💾 当前设备缓存状态:', cacheStatus);
    
    const iotMessages = await HuaweiCloudIoTService.getDeviceMessages();
    
    if (iotMessages && iotMessages.length > 0) {
      // 将IoT消息转换为MessageItem格式
      const convertedMessages: MessageItem[] = iotMessages.map(iotMsg => ({
        id: iotMsg.id,
        type: iotMsg.type,
        content: iotMsg.content,
        time: iotMsg.time,
        priority: iotMsg.type === 'error' ? 'high' : iotMsg.type === 'warning' ? 'medium' : 'low'
      }));
      
      // 检查消息是否有变化（通过内容和ID比较）
      const currentMessageIds = new Set(messageList.value.map(m => m.id));
      const hasNewMessages = convertedMessages.some(msg => !currentMessageIds.has(msg.id));
      
      // 如果有新消息或消息内容发生变化，则更新
      if (hasNewMessages || messageList.value.length === 0) {
        console.log('🆕 检测到新的IoT消息，更新消息列表');
        messageList.value = convertedMessages.slice(0, 2);
        
        console.log('✅ 成功更新华为云IoT设备消息:', {
          消息数量: convertedMessages.length,
          是否为新消息: hasNewMessages,
          消息详情: convertedMessages.map(m => ({ 
            id: m.id, 
            type: m.type, 
            content: m.content,
            time: m.time 
          }))
        });
      } else {
        console.log('📋 IoT消息无变化，保持当前消息列表');
      }
    } else {
      throw new Error('未获取到IoT设备消息');
    }
  } catch (error) {
    console.warn('⚠️ 获取华为云IoT设备消息失败，使用模拟数据:', error);
    console.error('详细错误信息:', error);
    
    // 使用模拟数据服务作为备用方案
    try {
      console.log('🤖 启用模拟数据服务...');
      const mockIoTMessages = MockDataService.generateMockIoTMessages();
      const mockMessageItems = MockDataService.convertToMessageItems(mockIoTMessages);
      
      // 检查消息是否有变化
      const currentMessageIds = new Set(messageList.value.map(m => m.id));
      const hasNewMessages = mockMessageItems.some(msg => !currentMessageIds.has(msg.id));
      
      if (hasNewMessages || messageList.value.length === 0) {
        console.log('🆕 模拟数据: 检测到新消息，更新消息列表');
        messageList.value = mockMessageItems.slice(0, 2);
        
        console.log('✅ 成功使用模拟IoT设备消息:', {
          消息数量: mockMessageItems.length,
          是否为新消息: hasNewMessages,
          消息详情: mockMessageItems.map(m => ({ 
            id: m.id, 
            type: m.type, 
            content: m.content,
            time: m.time 
          }))
        });
      } else {
        console.log('📋 模拟数据: 消息无变化，保持当前消息列表');
      }
    } catch (mockError) {
      console.error('❌ 模拟数据服务也失败:', mockError);
      
      // 最终备用方案：使用原始消息生成器
      if (messageList.value.length === 0) {
        messageList.value.unshift(MessageGenerator.generateMessage());
        if (messageList.value.length > 2) messageList.value = messageList.value.slice(0, 2);
      }
    }
  }
  
  buildingList.value = BuildingGenerator.generateBuildingStatus();
  await initCharts();
};

// 事件处理
const handleEnvCardClick = (type: keyof EnvData) => console.log('Environmental card clicked:', type)
const handleMessageClick = (message: MessageItem) => console.log('Message clicked:', message)
const handleBuildingClick = (building: BuildingStatus) => console.log('Building clicked:', building)
const handleChartRefresh = initCharts
const handleChartFullscreen = () => console.log('Chart fullscreen')
const handleChartReady = () => console.log('Chart ready')

//能耗统计时间延长
onMounted(async () => {
  await updateData()
  updateTimer = setInterval(updateData, 1000) // 改为1秒更新一次，实现实时监控
})

onUnmounted(() => {
  if (updateTimer) clearInterval(updateTimer)
})
</script>

<template>
  <div class="dashboard">
    <ParticleBackground :particle-count="20" />
    <TechScanEffect />
    <MainTitle />
    
    <div class="main-content">
      <div class="left-panel">
        <div class="env-cards-wrapper">
          <EnvCards :env-data="envData" @card-click="handleEnvCardClick" />
        </div>
        <div class="chart-wrapper">
          <ChartContainer chart-id="temperatureChart"
            :options="temperatureChartOptions" @refresh="handleChartRefresh" 
            @fullscreen="handleChartFullscreen" @chart-ready="handleChartReady" />
        </div>
        <div class="humidity-trend-wrapper">
          <HumidityTrend />
        </div>
      </div>

      <div class="center-panel">
        <div class="map-wrapper">
          <CampusMap :building-list="buildingList" @building-click="handleBuildingClick" />
        </div>
        <div class="env-quality-wrapper">
          <ChartContainer chart-id="environmentRadarChart"
            :options="environmentRadarOptions" @refresh="handleChartRefresh" 
            @fullscreen="handleChartFullscreen" @chart-ready="handleChartReady" />
        </div>
      </div>

      <div class="right-panel">
        <div class="message-wrapper">
          <MessagePanel :messages="messageList" @message-click="handleMessageClick" />
        </div>
        <div class="humidity-gauge-wrapper">
          <ChartContainer chart-id="humidityGaugeChart"
            :options="humidityGaugeOptions" @refresh="handleChartRefresh"
            @fullscreen="handleChartFullscreen" @chart-ready="handleChartReady" />
        </div>
        <div class="energy-wrapper">
          <ChartContainer chart-id="energyChart"
            :options="energyBarOptions" @refresh="handleChartRefresh" 
            @fullscreen="handleChartFullscreen" @chart-ready="handleChartReady" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.dashboard {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(45deg, #0a0a0a, #1a1a2e, #16213e);
  position: relative;
  overflow: hidden;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  display: flex;
  flex-direction: column;
}

.main-content {
  display: flex;
  height: calc(100vh - 130px);
  padding: 0.6vw;
  gap: 0.6vw;
  z-index: 10;
}

.left-panel, .right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.6vw;
}

.center-panel {
  flex: 1.8;
  display: flex;
  flex-direction: column;
  gap: 0.6vw;
}

/* 左侧面板 */
.env-cards-wrapper {
  flex: 0.7;
  border-radius: 0.4vw;
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(0, 212, 255, 0.2);
}

.left-panel .chart-wrapper {
  flex: 2;
  border-radius: 0.4vw;
  background: rgba(255, 107, 107, 0.05);
  border: 1px solid rgba(255, 107, 107, 0.2);
}

.humidity-trend-wrapper {
  flex: 2;
  border-radius: 0.4vw;
  background: rgba(103, 224, 227, 0.05);
  border: 1px solid rgba(103, 224, 227, 0.2);
}

/* 中间面板 */
.map-wrapper {
  flex: 2.8;
  border-radius: 0.4vw;
  background: rgba(0, 212, 255, 0.05);
  border: 1px solid rgba(0, 212, 255, 0.2);
}

.env-quality-wrapper {
  flex: 1.5;
  border-radius: 0.4vw;
  background: rgba(108, 92, 231, 0.05);
  border: 1px solid rgba(108, 92, 231, 0.2);
}

/* 右侧面板 */
.message-wrapper {
  flex: 0.5;
  border-radius: 0.4vw;
  background: rgba(255, 217, 61, 0.05);
  border: 1px solid rgba(255, 217, 61, 0.2);
}

.humidity-gauge-wrapper {
  flex: 2.2;
  border-radius: 0.4vw;
  background: rgba(103, 224, 227, 0.05);
  border: 1px solid rgba(103, 224, 227, 0.2);
}

.energy-wrapper {
  flex: 2.2;
  border-radius: 0.4vw;
  background: rgba(255, 182, 77, 0.05);
  border: 1px solid rgba(255, 182, 77, 0.2);
}

/* 响应式 */
@media (max-width: 1365px) {
  .env-cards-wrapper { flex: 0.6; }
  .left-panel .chart-wrapper { flex: 1.8; }
  .humidity-trend-wrapper { flex: 0.9; }
  .map-wrapper { flex: 1.3; }
  .env-quality-wrapper { flex: 2.5; }
  .message-wrapper { flex: 0.4; }
  .humidity-gauge-wrapper, .energy-wrapper { flex: 2.0; }
}

@media (max-width: 1023px) {
  .main-content {
    flex-direction: column;
    height: calc(100vh - 100px);
    overflow-y: auto;
  }
  
  .left-panel, .center-panel, .right-panel {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1vw;
  }
  
  .env-cards-wrapper, .humidity-trend-wrapper, .map-wrapper, 
  .env-quality-wrapper, .message-wrapper, .chart-wrapper,
  .humidity-gauge-wrapper, .energy-wrapper {
    height: 250px;
    flex: none;
  }
}
</style>


